package sifcom.json;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.Embedded;
import javax.persistence.Transient;

import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

public class ManejoJson<T> {

	static final int BAD_MODIFIERS = Modifier.FINAL | Modifier.STATIC | Modifier.TRANSIENT;
	
	protected Class<T> clazz;
	
	@SuppressWarnings("unchecked")
	public ManejoJson()
	{
		clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
	public ManejoJson(Class<T> clazz)
	{
		this.clazz = clazz;
	}
	
	public String setData(List<T> lst)
	{
		JSONObject json = new JSONObject();
		List<String> array= new ArrayList<String>();
		
		for(T entidad : lst)
		{
			
		for (Field field : clazz.getDeclaredFields())
		{
			// Ignore transient, embedded, array, and collection properties
			if (field.isAnnotationPresent(Transient.class)
				|| (field.isAnnotationPresent(Embedded.class))
				|| (field.getType().isArray())
				|| (Collection.class.isAssignableFrom(field.getType()))
				|| ((field.getModifiers() & BAD_MODIFIERS) != 0))
				continue;
			
			field.setAccessible(true);

			Object value;
			try
			{
				value = field.get(entidad);
			}
			catch (IllegalArgumentException e)
			{
				throw new RuntimeException(e);
			}
			catch (IllegalAccessException e)
			{
				throw new RuntimeException(e);
			}
			if (value != null)
			{
				try {
					/*if(field.getType().equals(Key.class))
					{
						com.google.appengine.api.datastore.Key key = KeyFactory.createKey("Provincia",value.toString());
						json.put(field.getName(),"jhon "+ KeyFactory.keyToString(key).toString());
						
					}
					else*/
					json.put(field.getName(), value);		
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}	
		
		array.add(json.toString());
		
		}
		/*
		JSONObject success = new JSONObject();
		JSONObject message = new JSONObject();
		JSONObject data = new JSONObject();
		try{		
		success.put("success", true);				
		success.put("message", "Datos Cargados");
		data.put("data", array.toString());
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		
		JSONArray myOut = new JSONArray();
		myOut.put(success.toString());
		myOut.put(message.toString());
		myOut.put(data.toString());*/
		
		String myOut = "{\"success\":true,\"message\":\"Load Data 2\",\"data\":"+array.toString()+"}"; 
		
		return myOut;
	}	

	public void setData(T entidad,JSONObject jsonSocio) throws JSONException
	{
		for (Field field : clazz.getDeclaredFields())
		{
			// Ignore transient, embedded, array, and collection properties
			if (field.isAnnotationPresent(Transient.class)
				|| (field.isAnnotationPresent(Embedded.class))
				|| (field.getType().isArray())
				|| (Collection.class.isAssignableFrom(field.getType()))
				|| ((field.getModifiers() & BAD_MODIFIERS) != 0)
				|| field.getName().equalsIgnoreCase("id"))
				continue;
			
			field.setAccessible(true);

			try 
			{ 
				if(!jsonSocio.isNull(field.getName()))
					try {
						if(field.getType().equals(Integer.class))
						field.set(entidad,new Long(jsonSocio.get(field.getName()).toString()));
						
						if(field.getType().equals(String.class))
							field.set(entidad,jsonSocio.get(field.getName()).toString());
						
						if(field.getType().equals(Long.class))
							field.set(entidad,new Long(jsonSocio.get(field.getName()).toString()));
						
						//if(field.getType().equals(Key.class))
							//field.set(entidad, new Key<Class<T>>((Class<? extends Class<T>>) clazz,new Long(jsonSocio.get(field.getName()).toString())));
							//field.set(entidad,new Long(jsonSocio.get(field.getName()).toString()));
						//new Key<Class<T>>((Class<? extends Class<T>>) clazz,new Long(jsonSocio.get(field.getName()).toString()));
						
					} catch (SecurityException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				
			}
			catch (IllegalArgumentException e)
			{
				throw new RuntimeException(e);
			}
			catch (IllegalAccessException e)
			{
				throw new RuntimeException(e);
			}
		}			
	
	}
}
